package com.unicom.priceboard.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.Calendar;

public class ReadFileUtil {
	
   public static String readSessionFile(String sessionFilePath) { 
	   String strLine="0";
      try{
    	File checkfile =new File(sessionFilePath);
    	if(checkfile.exists()){
		    FileInputStream fstream = new FileInputStream(sessionFilePath);
		    DataInputStream in = new DataInputStream(fstream);
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));
		    strLine=br.readLine();
		    in.close();
    	}
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
    return strLine;
  }
   
   /**
    * Create session.txt file with provided session
    * @param numbersession
    * @param sessionFilePath
    */
   public static void writeSessionFile(String numbersession, String sessionFilePath){
	   try{
		   File checkfile =new File(sessionFilePath);
		   if(!checkfile.exists()){
			   if(!checkfile.createNewFile()){
				   System.out.println("not create new file");
			   }
		   }   
		   if(!isUpToDate(sessionFilePath)){
			   FileOutputStream fout =new FileOutputStream(sessionFilePath);
			   DataOutputStream out=new DataOutputStream(fout);
			   out.writeBytes(numbersession);
			   out.close();
		   }
	   }catch (Exception e ){
		   System.err.println("Error: " + e.getMessage());
	   }
   }
   
   
   /**
    *  Check if a file is up-to-date or not
	 * @param filePath
	 * @return true if file is up-to-date otherwise false
	 */
	public static boolean isUpToDate(String filePath){
		File checktime = new File(filePath);
		if (!checktime.exists()) {
			return false;
		}
		Calendar lastModified = Calendar.getInstance();
		lastModified.setTimeInMillis(checktime.lastModified());
		Calendar today = Calendar.getInstance();
		if (lastModified.get(Calendar.YEAR) < today.get(Calendar.YEAR)) {
			return false;
		}
		if (lastModified.get(Calendar.MONTH) < today.get(Calendar.MONTH)) {
			return false;
		}
		if (lastModified.get(Calendar.DAY_OF_MONTH) < today.get(Calendar.DAY_OF_MONTH)) {
			return false;
		}
		return true;
	}
}